package life.majiang.community.controller;

import life.majiang.community.cache.HotTagCache;
import life.majiang.community.dto.PaginationDTO;
import life.majiang.community.dto.QuestionDTO;
import life.majiang.community.model.User;
import life.majiang.community.service.NotificationService;
import life.majiang.community.service.QuestionService;
import life.majiang.community.service.UserService;
import life.majiang.community.utils.BtoaEncodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by codedrinker on 2019/4/24.
 */
@Controller
public class IndexController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private HotTagCache hotTagCache;

    @Autowired
    private AuthorizeController authorizeController;

    @Autowired
    private UserService userService;

    @Autowired
    private NotificationService notificationService;

    @GetMapping("/")
    public String index(Model model,
                        @RequestParam(name = "page", defaultValue = "1") Integer page,
                        @RequestParam(name = "size", defaultValue = "10") Integer size,
                        @RequestParam(name = "search", required = false) String search,
                        @RequestParam(name = "tag", required = false) String tag,
                        @RequestParam(name = "sort", required = false) String sort,
                        HttpServletRequest request,
                        @RequestParam(name = "token",required = false) String token) throws NoSuchFieldException, IllegalAccessException {
        PaginationDTO<QuestionDTO> pagination = questionService.list(search, tag, sort, page, size);
        PaginationDTO<QuestionDTO> hots = questionService.list("", "", "hot", 1, size);
        List<String> tags = hotTagCache.getHots();
        model.addAttribute("search", search);
        model.addAttribute("tag", tag);
        model.addAttribute("tags", tags);
        model.addAttribute("sort", sort);
        model.addAttribute("hots", hots);
        HttpSession session = request.getSession();
        User userSession = (User) session.getAttribute("user");
        User currentUser;
        if (userSession == null) {
            User user = new User();
            String data = BtoaEncodeUtil.decrypt(token);
            Map<String, String> map = new HashMap<>();
            String[] params = data.split("&");

            for(int i = 0; i < params.length; i++){
                String[] secondParams = params[i].split("=");
                map.put(secondParams[0], secondParams[1]);
            }

            Class<User> clazz = User.class;

            for (Map.Entry<String, String> entry : map.entrySet()) {
//                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                Field field = clazz.getDeclaredField(entry.getKey());
                field.setAccessible(true);
                field.set(user, entry.getValue());
            }

            userService.createOrUpdate(user);
            User user1 = userService.findByAccountId(user.getAccountId());
            session.setAttribute("user", user1);
            currentUser = user1;
            Long unreadCount = notificationService.unreadCount(user1.getId());
            session.setAttribute("unreadCount", unreadCount);
        }else {
            Long unreadCount = notificationService.unreadCount(userSession.getId());
            session.setAttribute("unreadCount", unreadCount);
            currentUser = userSession;
        }
        List<QuestionDTO> questionDTOs = pagination.getData();
        for(QuestionDTO questionDTO : questionDTOs){
            if(questionDTO.getUser().getId().equals(currentUser.getId())){
//            if(questionDTO.getUser().getId().equals("sysadmin")){
                questionDTO.setAnonymous(false);
            }else{
                questionDTO.setAnonymous(questionDTO.getLikeCount() == 1);
            }
        }
        model.addAttribute("pagination", pagination);
        return "index";
    }

//    @GetMapping("/like")
//    public String getLike(){
//        return "ceshi";
//    }
//
//    @GetMapping("/like/count")
//    public void like(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//        String s = request.getHeader("token");
//        System.out.println(s);
//        RequestDispatcher dispatcher = request.getRequestDispatcher("https://www.baidu.com");
//        dispatcher.forward(request, response);
//    }
}
